package com.nuatar.meibi.Thread;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import com.nuatar.meibi.pubvar.ImagePair;
import com.nuatar.meibi.pubvar.PhoneMaster;

public class MultiDownloader {
	int filesize;
	int Downloadsize = 0;
	URL murl;
	DownloadThread[] Threads;
	ByteArrayOutputStream[] byteOut;
	String savePath;
	int threadnum;
	DownloadListener dl;
	ThreadListener tl;
	RandomAccessFile af;
	ImagePair ip;

	public MultiDownloader(URL urls, String savePaths, int ThreadNum,
			DownloadListener dls, ImagePair ips) {
		murl = urls;
		savePath = savePaths;
		threadnum = ThreadNum;
		ip = ips;
		if (threadnum <= 0) {
			threadnum = 1;
		}
		Threads = new DownloadThread[threadnum];
		byteOut = new ByteArrayOutputStream[threadnum];

		dl = dls;
		try {
			HttpURLConnection cnn = (HttpURLConnection) murl.openConnection();
			cnn.setConnectTimeout(5 * 1000);
			cnn.setRequestMethod("GET");
			cnn.setRequestProperty(
					"Accept",
					"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
			cnn.setRequestProperty("Accept-Language", "zh-CN");
			cnn.setRequestProperty("Referer", murl.toString());
			cnn.setRequestProperty("Charset", "UTF-8");
			cnn.setRequestProperty("User-Agent", "baidu-bcs-java-sdk/1");
			cnn.setRequestProperty("Connection", "Keep-Alive");
			cnn.connect();
			this.filesize = cnn.getContentLength();
			af = new RandomAccessFile((new File(savePath)), "rw");
			af.setLength(filesize);
			tl = new ThreadListener() {
				@Override
				public void ReportProgress(int downloadsize, int Threadid) {
					// TODO 自动生成的方法存根
					Downloadsize = getDownloadSizeAll();
					dl.ReportProcess(Downloadsize, ip.Length);
				}

				@Override
				public void DownLoadResult(boolean rsult, int Threadid)
						throws IOException {
					// TODO 自动生成的方法存根
					if (rsult) {
						byteOut[Threadid] = Threads[Threadid].getOutstream();
						ByteArrayOutputStream ball = new ByteArrayOutputStream();
						if (getResult()) {

							for (ByteArrayOutputStream bo : byteOut) {
								ball.write(bo.toByteArray());
								ball.flush();
							}
							af.seek(ip.Seeker);
							af.write(ball.toByteArray());
							af.close();
							dl.DownloadResult(true);
						}

					}
				}

				@Override
				public void ErrorLog(Exception e, int Threadid) {
					// TODO 自动生成的方法存根
					dl.ErrorLog(e);
				}

			};
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void Start() {
		if (PhoneMaster.VerifyImage(savePath, ip)) {
			dl.DownloadResult(true);
		} else {

			int block = ip.Length / this.threadnum;
			for (int i = 0; i < this.threadnum; i++) {
				int start = i * block + ip.Seeker;
				int length = block;
				if (i == this.threadnum - 1) {
					length = ip.Length + ip.Seeker - start;
				}
				Threads[i] = new DownloadThread(tl, murl, start, length, i);
				Threads[i].start();
			}

		}
	}

	public void Stop() {

	}

	public void Pause() {

	}

	public boolean getResult() {
		boolean r = true;
		for (int i = 0; i < this.Threads.length; i++) {
			r = r && Threads[i].isFinish();
		}
		return r;

	}

	public int getDownloadSizeAll() {
		int result = 0;
		for (int i = 0; i < this.Threads.length; i++) {
			result += Threads[i].downloadSize;
		}
		return result;
	}

	public interface ThreadListener {
		public void ReportProgress(int downloadsize, int Threadid);

		public void DownLoadResult(boolean rsult, int Threadid)
				throws IOException;

		public void ErrorLog(Exception e, int Threadid);
	}

}
